package com.lei.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lei.oss.service.OssService;
import com.lei.oss.utils.ConstantUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
@Service
public class OssServiceImpl implements OssService {


    //上传文件到OSS
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        String endPoint = ConstantUtil.END_POINT;
        String accessKeyId = ConstantUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantUtil.BUCKET_NAME;



        try {
            //
            String filename = UUID.randomUUID().toString().replaceAll("-","")+file.getOriginalFilename();
            //把文件按日期分类
            String currentTime = new DateTime().toString("yyyy/MM/dd");

            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName,currentTime+"/"+filename,inputStream);
            ossClient.shutdown();

            String url ="https://"+bucketName+"."+endPoint+"/"+currentTime+"/"+filename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
